package com.ihrm.system.controller;


import com.ihrm.common.controller.BaseController;
import com.ihrm.common.entity.PageResult;
import com.ihrm.common.entity.Result;
import com.ihrm.common.entity.ResultCode;
import com.ihrm.common.exception.CommonException;
import com.ihrm.common.utils.JwtUtils;
import com.ihrm.domain.system.po.User;
import com.ihrm.domain.system.vo.ProfileResult;
import com.ihrm.domain.system.vo.UserResult;
import com.ihrm.system.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

//1.解决跨域
@CrossOrigin
//2.声明restContoller
@RestController
//3.设置父路径
@RequestMapping(value = "/sys")
public class UserController extends BaseController
{

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    //测试通过系统微服务调用企业微服务方法

    /**
     * 用户登录
     * 1.通过service根据mobile查询用户
     * 2.比较password
     * 3.生成jwt信息
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(@RequestBody Map<String, String> loginMap) {
        String mobile = loginMap.get("mobile");
        String password = loginMap.get("password");
        // 1. 构造登录令牌
        password = new Md5Hash(password,mobile,3).toString();
//        password = BCrypt.hashpw(password, BCrypt.gensalt());
        UsernamePasswordToken upToken = new UsernamePasswordToken(mobile, password);

        try {
            // 2. 获取subject
            Subject subject = SecurityUtils.getSubject();
            // 3. 调用login方法进入realm完成认证
            subject.login(upToken);
            // 4. 获取sessionId，构造返回结果
            String sessionId = String.valueOf(subject.getSession().getId());
            return new Result(ResultCode.SUCCESS,sessionId);
        }catch (Exception e){
            return new Result(ResultCode.MOBILEORPASSWORDERROR);
        }

        // 下面方法是通过jwt令牌+ redis来进行登录
//        User user = userService.findByMobile(mobile);
//        if (user == null || !userService.passwordIsOk(password,user.getPassword())) {
//            // error
//            return new Result(ResultCode.MOBILEORPASSWORDERROR);
//        } else {
//            // successed
//            StringBuilder sb = new StringBuilder();
//            // 获取到所有的可以访问的API权限
//            for (Role role : user.getRoles()) {
//                for (Permission permission : role.getPermissions()) {
//                    if (permission.getType() == PermissionConstants.PERMISSION_API) {
//                        sb.append(permission.getCode()).append(",");
//                    }
//                }
//            }
//            Map<String,Object> hashMap = new HashMap();
//            hashMap.put("apis",sb); // 可访问呢的权限
//            hashMap.put("CompanyId",user.getCompanyId());
//            hashMap.put("CompanyName",user.getCompanyName());
//            String token = jwtUtils.createJwt(user.getId(),user.getUsername(),hashMap);
//            return new Result(ResultCode.SUCCESS,token);
//        }

    }

    /**
     * 用户登录成功之后，获取用户信息 1.获取用户id 2.根据用户id查询用户 3.构建返回值对象 4.响应
     */
    @RequestMapping(value = "/profile", method = RequestMethod.POST)
    public Result profileUser(HttpServletRequest request) throws CommonException {
        // jwt的方式获取
//        Claims claims = this.claims;
//        String userId = claims.getId();
//        User user = userService.findById(userId);
//        return new Result(ResultCode.SUCCESS,new ProfileResult(user));
        // shiro的方式获取 session中的安全数据集合
        Subject subject = SecurityUtils.getSubject();
        // 获取安全数据集合
        PrincipalCollection principalCollection = subject.getPrincipals();
        // 获取安全数据
        ProfileResult primaryPrincipal = (ProfileResult)principalCollection.getPrimaryPrincipal();

        return new Result(ResultCode.SUCCESS,primaryPrincipal);
    }

    /**
     * 分配角色
     */
    @RequestMapping(value = "/user/assignRoles", method = RequestMethod.PUT)
    public Result assignRoles(@RequestBody Map<String, Object> map) {
        //1.获取被分配的用户id
        String userId = (String) map.get("id");
        //2.获取到角色的id列表
        List<String> roleIds = (List<String>) map.get("roleIds");
        //3.调用service完成角色分配
        userService.assignRoles(userId, roleIds);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 保存用户
     */
    @RequestMapping(value = "/user", method = RequestMethod.POST, name = "user")
    public Result save( @RequestBody User user) {
        //1.设置保存的企业id
        // 暂时设置为固定值
        user.setCompanyId(this.companyId);
        user.setCompanyName(this.companyName);
        //2.调用service完成保存企业
        userService.save(user);
        //3.构造返回结果
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 查询企业的部门列表 指定企业id
     */
    @RequestMapping(value = "/user",method = RequestMethod.GET)
    public Result findAll(int page, int size,@RequestParam Map map) {
        //1.获取当前的企业id
        map.put("companyId", this.companyId);
        //2.完成查询
        Page<User> pageUser = userService.findAll(map, page, size);
        //3.构造返回结果
        PageResult<User> pageResult = new PageResult<>(pageUser.getTotalElements(), pageUser.getContent());
        return new Result(ResultCode.SUCCESS, pageResult);
    }

    /**
     * 根据ID查询user
     */
    @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
    public Result findById(@PathVariable(value = "id") String id) {
        final User user = userService.findById(id);
        final UserResult userResult = new UserResult(user);
        return new Result(ResultCode.SUCCESS, userResult);
    }

    /**
     * 修改User
     */
    @RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
    public Result update(@PathVariable(value = "id") String id, @RequestBody User user) {
        //1.设置修改的部门id
        user.setId(id);
        //2.调用service更新
        userService.update(user);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 根据id删除
     */
    @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable(value = "id") String id) {
        userService.deleteById(id);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 查询
     * @param page
     * @param pagesize
     * @param map
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/value", method = RequestMethod.GET)
    public Result findByPage(int page, int pagesize, @RequestParam Map<String, Object> map) throws Exception {
        map.put("companyId", this.companyId);
        final Page<User> searchPage = userService.findAll(map, page, pagesize);
        final PageResult<User> pr = new PageResult<>(searchPage.getTotalElements(), searchPage.getContent());
        return new Result(ResultCode.SUCCESS, pr);
    }
}
